import UIKit
//https://blog.csdn.net/github_36850997/article/details/95048331
var numbers: [Int?] = [1, nil, 2, 35, nil]
print(numbers)

var obj: [String: Any?] = ["name": nil, "age": 18]
print(obj)

obj["sex"] = nil
//obj.updateValue(nil, forKey: "sex")
print(obj)

print("====================")


import UIKit


var array1 = ["1","2","3","4","5"];

// 1 if let 是一个组合关键字 来进行可选绑定
// 解决Optional对象解包时产生空对象的处理。
for  i in array1 {
    print(i);
}

if let idx = array1.firstIndex(of: "4"){
    print("----4:",idx);
}

// 2 绑定多个值
if let idx  = array1.firstIndex(of: "2"), idx != array1.endIndex{
    print(idx);
}

// 3 while let 表示一个条件返回nil时候终止循环
var array2 = ["8","9","10"];
var iterator = array2.makeIterator();
while let idx = iterator.next() {
    // 8 9 10
    print(idx)
}

// 4 双重可选值
// 一个可选值本身被另外一个可选值包装起来，导致可选值嵌套在可选值当中
var intArray1 = ["Home","708","2019"];
// 将上面的数组转换为一个整数的数组，只有是整数的字符串才能成功被转换，否则转换结果为nil
// 结果是optional<Int>
let mapIntArray1 =  intArray1.map{Int($0)};
// [nil, Optional(708), Optional(2019)]
print(mapIntArray1);
var itemrator1 = mapIntArray1.makeIterator();
// 之所以nil 被打印出来，是因为从遍历器返回的是一个非nil值,是 .some(nil)
while let item = itemrator1.next() {
    //nil Optional(708) Optional(2019)
    print(item as Any);
}


// case 模式匹配筛选出nil值
for case nil in mapIntArray1
{
    print("为nil");
}

// case筛选出不为nil的值
for case let i?  in mapIntArray1{
    // 708 2019
    print(i);
}

print("*********************")


class Car {
    var engine: String?
}

class Person {
    var car: Car?
}

let person: Person? = Person()
//let engine: String?? = person?.car?.engine
let engine = person?.car?.engine

// 使用可选绑定
if let car = person?.car, let engine = car.engine {
    print("Engine is: \(engine)")
} else {
    print("Either person or car is nil, or engine is nil.")
}

// 使用as?进行安全的类型转换
if let engine = (person?.car as? Car)?.engine {
    print("Engine is: \(engine)")
} else {
    print("Either person or car is nil, or engine is nil.")
}





